package com.lw.leetcode.arr.b;

import java.util.HashMap;
import java.util.Map;

/**
 * 525. 连续数组
 * 剑指 Offer II 011. 0 和 1 个数相同的子数组
 *
 * @Author liw
 * @Date 2021/6/3 11:12
 * @Version 1.0
 */
public class FindMaxLength {

    public static void main(String[] args) {
        FindMaxLength test = new FindMaxLength();
//        int[] arr = {1};
//        int[] arr = {1, 0};
//        int[] arr = {1, 0, 1};
        int[] arr = {1, 1,  1, 0, 1, 1, 1,0,  1, 1, 0, 1};
        int maxLength = test.findMaxLength(arr);
        System.out.println(maxLength);
    }

    

    /**
     *
     * @param nums
     * @return
     */
    public int findMaxLength(int[] nums) {
        int length = nums.length;
        Map<Integer, Integer> map = new HashMap<>(length << 1);
        int sum = 0;
        map.put(0, -1);
        int max = 0;
        for (int i = 0; i < length; i++) {
            int num = nums[i];
            sum += ((num << 1) - 1);
            Integer value = map.get(sum);
            if (value == null) {
                map.put(sum, i);
            } else {
                max = max < i - value ? i - value : max;
            }
        }
        return max;
    }

    public int findMaxLength2(int[] nums) {
        int length = nums.length;
        Map<Integer, Integer> map = new HashMap<>(length << 1);
        int sum = 0;
        map.put(0, -1);
        int max = 0;
        for (int i = 0; i < length; i++) {
            int num = nums[i];
            if (num == 1) {
                sum++;
            } else {
                sum--;
            }
            Integer value = map.get(sum);
            if (value == null) {
                map.put(sum, i);
            } else {
                max = Math.max(max, i - value);
            }
        }
        return max;
    }


}
